<template>
    <div class="p-2">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item label="插件名称" prop="pluginsName">
                <el-input v-model="queryParams.pluginsName" placeholder="请输入插件名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="版本号" prop="pluginsVersion">
                <el-input v-model="queryParams.pluginsVersion" placeholder="请输入插件版本号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>
  
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['order:plugins:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button color="#626aef" :dark="false" :disabled="single" plain icon="Share" @click="handleShare" v-if="userId == 1">分享</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['order:plugins:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['order:plugins:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['order:plugins:export']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>
  
        <el-table v-loading="loading" :data="pluginsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="插件名称" align="center" prop="pluginsName" />
          <el-table-column label="插件版本号" align="center" prop="pluginsVersion" />
          <el-table-column label="插件下载地址" align="center" prop="pluginsDownloadLink" />
          <el-table-column label="插件简介" align="center" prop="blurb" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:plugins:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:plugins:remove']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
  
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
      <!-- 添加或修改插件对话框 -->
      <el-dialog :title="dialog.title" v-if="dialog.visible" v-model="dialog.visible" width="500px" append-to-body>
        <el-form ref="pluginsFormRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="插件名称" prop="pluginsName">
            <el-input v-model="form.pluginsName" placeholder="请输入插件名称" />
          </el-form-item>
          <el-form-item label="版本号" prop="pluginsVersion">
            <el-input v-model="form.pluginsVersion" placeholder="请输入插件版本号" />
          </el-form-item>
          <el-form-item label="简介" prop="blurb">
            <el-input type="textarea" :rows="4" v-model="form.blurb" placeholder="请输入插件版本号" />
          </el-form-item>
          <el-form-item label="附件" prop="pluginsDownloadLink">
            <el-upload
              style="width: 300px"
              class="upload-demo"
              drag
              :show-file-list="false"
              :limit="1"
              :headers="headers"
              :on-success="(res, file) => handleUploadSuccess(res, file, 'pluginsDownloadLink')"
              :action="uploadUrl"
              multiple
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽或 <em>点击上传</em></div>
              <!-- <div class="el-upload__text">文件名不能包含特殊符号</div> -->
            </el-upload>
            <div>
              <a style="color: #409eff;" v-if="form.pluginsDownloadLink" :href="form.pluginsDownloadLink" target="_blank">{{getFileName()}}</a>
              <el-button v-if="form.pluginsDownloadLink" icon="Delete" link type="danger" @click="form.pluginsDownloadLink = ''"></el-button>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup name="Plugins" lang="ts">
  import { listPlugins, getPlugins, delPlugins, addPlugins, updatePlugins,sharePlugins } from '@/api/goods/plugins';
  import { PluginsVO, PluginsQuery, PluginsForm } from '@/api/goods/plugins/types';
  import { globalHeaders } from '@/utils/request';
  import useUserStore from '@/store/modules/user';

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  
  const headers = globalHeaders();
  const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload';
  const fileList = ref([])
  const userStore = useUserStore();
  const userId = userStore?.sysTenantVo?.id;
  
  const pluginsList = ref<PluginsVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  
  const queryFormRef = ref<ElFormInstance>();
  const pluginsFormRef = ref<ElFormInstance>();
  
  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  
  const initFormData: PluginsForm = {
    id: undefined,
    pluginsName: undefined,
    pluginsVersion: undefined,
    blurb: undefined,
    pluginsDownloadLink: undefined,
  }
  const data = reactive<PageData<PluginsForm, PluginsQuery>>({
    form: {...initFormData},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      pluginsName: undefined,
      pluginsVersion: undefined,
      params: {
      }
    },
    rules: {
      id: [
        { required: true, message: "主键id不能为空", trigger: "blur" }
      ],
      pluginsName: [
        { required: true, message: "插件名称不能为空", trigger: "blur" }
      ],
      pluginsVersion: [
        { required: true, message: "插件版本号不能为空", trigger: "blur" }
      ],
    }
  });
  
  const { queryParams, form, rules } = toRefs(data);
  
  /** 查询插件列表 */
  const getList = async () => {
    loading.value = true;
    const res = await listPlugins(queryParams.value);
    pluginsList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }
  
  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }
  
  /** 表单重置 */
  const reset = () => {
    form.value = {...initFormData};
    pluginsFormRef.value?.resetFields();
  }
  
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  
  /** 多选框选中数据 */
  const handleSelectionChange = (selection: PluginsVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加插件";
  }
  
  /** 修改按钮操作 */
  const handleUpdate = async (row?: PluginsVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getPlugins(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改插件";
  }
  
  /** 提交按钮 */
  const submitForm = () => {
    pluginsFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updatePlugins(form.value).finally(() =>  buttonLoading.value = false);
        } else {
          await addPlugins(form.value).finally(() =>  buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    });
  }
  
  /** 删除按钮操作 */
  const handleDelete = async (row?: PluginsVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除插件编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delPlugins(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }
  
  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('order/plugins/export', {
      ...queryParams.value
    }, `plugins_${new Date().getTime()}.xlsx`)
  }
  const handleUploadSuccess = (res, file, key)=>{
      // 如果上传成功
      if (res.code == 200) {
        form.value[key] = res.data.url;
      } else {
        proxy?.$modal.msgError(res.msg);
      }
    }
  const downloadFile = () => {
    window.open(form.value.pluginsDownloadLink, '_blank');
  };
  const getFileName = () => {
    return form.value.pluginsDownloadLink?.substring(form.value.pluginsDownloadLink.lastIndexOf('/') + 1);
  }
  const handleShare = () => {
    proxy?.$modal.confirm('是否确认分享插件？').finally(() => {
      sharePlugins(ids.value).then(res=>{
        if(res.code == 200) {
          proxy?.$modal.msgSuccess("分享成功");
        }
      })
    });
  }
  onMounted(() => {
    getList();
  });
  </script>
  